import React from 'react'
import { Button, Row, Divider, message, Col, Icon, Input, Progress, Table, Tabs, Tag, Statistic } from 'antd'
import Highlighter from 'react-highlight-words'
import _ from 'lodash'
import { FormattedMessage } from 'react-intl'
import { convertContent } from '../../../../../constant/lang-util'

const {TabPane} = Tabs

export default class AssignmentsBasicQuizzesOverviewBox extends React.Component {
  state = {
    searchText: '',
    currentAssignmentId: -1
  }

  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({setSelectedKeys, selectedKeys, confirm, clearFilters}) => (
      <div style={{padding: 8}}>
        <Input
          ref={node => {
            this.searchInput = node
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
          style={{width: 188, marginBottom: 8, display: 'block'}}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm)}
          icon="search"
          size="small"
          style={{width: 90, marginRight: 8}}
        >
          Search
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{width: 90}}>
          Reset
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{color: '#1890ff'}}/>
    ),
    onFilter: (value, record) => (record[dataIndex] || '')
      .toString()
      .toLowerCase()
      .includes(value.toLowerCase())
    ,
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select())
      }
    }
    ,
    render: text => (
      <Highlighter
        highlightStyle={{backgroundColor: '#ffc069', padding: 0}}
        searchWords={[this.state.searchText]}
        autoEscape
        textToHighlight={text.toString()}
      />
    ),
  })

  handleSearch = (selectedKeys, confirm) => {
    confirm()
    this.setState({searchText: selectedKeys[0]})
  }

  handleReset = clearFilters => {
    clearFilters()
    this.setState({searchText: ''})
  }

  formatTags = (item) => {
    if (!item) return ''

    const tagColors = item.split(',')

    return tagColors.map(item => {
      const tagColor = item.split('|')
      return <Tag color={tagColor[1]}>{tagColor[0]}</Tag>
    })
  }
  getBasicQuizLink = record => {
    const {programId} = this.props
    return `https://school.thoughtworks.cn/learn/program-center/basicQuiz/index.html#/tutor/program/${programId}/task/${record.taskId}/student/${record.studentId}/divider/assignment/${record.assignmentId}/quiz/0`
  }

  getColumns = () => {
    const colomns = [{
      title: <FormattedMessage id='排名'/>,
      render: (text, record, index) => {
        return <div>{index + 1}</div>
      }
    },
      {
        title: <FormattedMessage id='姓名'/>,
        dataIndex: 'userName',
        width: 100,
        key: 'name',
        render: (text, record) => {
          return <a target='_blank' href={this.getBasicQuizLink(record)}>{text}</a>
        }
      }, {
        title: 'Tag',
        dataIndex: 'tag',
        width: 200,
        ...this.getColumnSearchProps('tag'),
        render: (item) => {
          return <span>{this.formatTags(item)}</span>
        }
      }, {
        title: <FormattedMessage id='题目总数'/>,
        width: 200,
        dataIndex: 'total'
      }, {
        title: <FormattedMessage id='未完成数量'/>,
        width: 200,
        dataIndex: 'unFinish',
        render: (total, record) => {
          return <span>{record.total - record.correctCount - record.wrongCount}</span>
        }
      }, {
        title: <FormattedMessage id='正确个数'/>,
        width: 200,
        sorter: (a, b) => a.correctCount - b.correctCount,
        dataIndex: 'correctCount'
      }, {
        title: <FormattedMessage id='错误个数'/>,
        width: 200,
        dataIndex: 'wrongCount'
      }, {
        title: <FormattedMessage id='正确率'/>,
        width: 200,
        render: (text, record) => {
          const {correctCount, wrongCount} = record
          const percent = ((correctCount / (correctCount + wrongCount)).toFixed(2)) * 100
          return <Progress
            percent={parseInt(percent)}
          />
        }
      }]

    return colomns
  }

  getCurrentAssignment = currentAssignmentId => {
    const {assignmentsBasicQuizzesOverview} = this.props
    let filterAssignments = assignmentsBasicQuizzesOverview.filter(item => item.assignmentId === currentAssignmentId)
    filterAssignments.sort((a, b) => b.correctCount - a.correctCount)
    return filterAssignments
  }
  getCurrentAssignmentId = () => {
    const {currentAssignmentId} = this.state
    const {assignmentsBasicQuizzesOverview} = this.props
    return currentAssignmentId > 0
      ? currentAssignmentId
      : assignmentsBasicQuizzesOverview[0].assignmentId
  }

  statisticCorrectRate = dataSource => {
    const {searchText} = this.state

    return searchText === ''
      ? dataSource.map(item => (item.correctCount / (item.correctCount + item.wrongCount)) * 100)
      : dataSource.filter(item => (item.tag || '').includes(searchText))
        .map(item => (item.correctCount / (item.correctCount + item.wrongCount)) * 100)
  }

  showStatistic = dataSource => {
    const studentsCorrectRate = this.statisticCorrectRate(dataSource)
    const total = studentsCorrectRate.length
    return <Row type='flex' justify='center'>
      <Col span={2}>
        <Statistic title="总人数" value={total}/>

      </Col>
      <Col span={4}>
        <Statistic title="正确率大于90%" value={studentsCorrectRate.filter(item => item >= 90).length}
                   suffix={` / ${total}`}/>

      </Col>
      <Col span={4}>
        <Statistic title="正确率70% ～ 90%"
                   value={studentsCorrectRate.filter(item => item >= 70 && item < 90).length}
                   suffix={` / ${total}`}/>

      </Col>
      <Col span={4}>
        <Statistic title="正确率60% ～ 70%"
                   value={studentsCorrectRate.filter(item => item >= 60 && item < 70).length}
                   suffix={` / ${total}`}/>

      </Col>
      <Col span={4}>
        <Statistic title="正确率30% ～ 60%"
                   value={studentsCorrectRate.filter(item => item >= 30 && item < 60).length}
                   suffix={` / ${total}`}/>

      </Col>
      <Col span={3}>
        <Statistic title="正确率小于30%"
                   value={studentsCorrectRate.filter(item => item < 30 || isNaN(item)).length}
                   suffix={` / ${total}`}/>
      </Col>
      <Divider/>
    </Row>
  }

  render () {
    const {assignmentsBasicQuizzesOverview} = this.props
    return <div>
      <Tabs tabPosition='left'
            onChange={currentAssignmentId => this.setState({
              currentAssignmentId,
              searchText: ''
            })}>
        {
          _.uniqBy(assignmentsBasicQuizzesOverview, 'assignmentId').map((item, i) => {
              const dataSource = this.getCurrentAssignment(item.assignmentId)
              return <TabPane tab={
                <span>
                  <span>
                      <span style={{float: 'left'}}>{item.taskTitle}</span><br/>
                      <span style={{fontSize: 12, fontWeight: 'lighter'}}>{item.assignmentTitle}</span>
                  </span>
                  <Divider type='vertical'/>
                  <a onClick={() => this.props.getAssignmentsBasicQuizzesStatus(item)}>{convertContent('详情')}</a>
                </span>
              } key={item.assignmentId}>
                {
                  this.showStatistic(dataSource)
                }
                <Table
                  columns={this.getColumns()}
                  dataSource={dataSource}
                  rowKey={item => item.studentId}
                  bordered
                  pagination={false}
                  size='small'
                />
              </TabPane>
            }
          )
        }
      </Tabs>
    </div>

  }
}
